# File       : page_data_login_new.py
# Time       ：2025/7/14 15:46
# Author     ：shimingliang
# version    ：python 3.6
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException


class UserLoginPage:
	"""登录页面对象模型"""

	# 页面元素定位器
	_locators = {
		"username": (By.ID, "username"),
		"password": (By.NAME, "password"),
		"login_button": (By.TAG_NAME, "button"),
		"success_message": (By.XPATH, "/html/body/div/div/aside/div[1]/a"),
		"username_error": (By.XPATH, "/html/body/div/div/div/form/div[1]/span[1]"),
		"password_error": (By.XPATH, "/html/body/div/div/div/form/div[2]/span[1]")
	}

	def __init__ (self, driver):
		self.driver = driver
		self.wait = WebDriverWait(driver, 10, 0.5)


	def login (self, username: str, password: str):
		"""执行登录操作"""
		self._clear_and_type(self._locators[ "username" ], username)
		self._clear_and_type(self._locators[ "password" ], password)
		self.driver.find_element(*self._locators[ "login_button" ]).click()


	def _clear_and_type (self, locator, text):
		"""清空并输入文本"""
		element = self.wait.until(EC.visibility_of_element_located(locator))
		element.clear()
		element.send_keys(text)


	def get_success_message (self) -> str:
		"""获取登录成功后的用户信息"""
		try:
			return self.wait.until(
				EC.visibility_of_element_located(self._locators[ "success_message" ])
			).text
		except TimeoutException:
			return ""


	def get_username_error_message (self) -> str:
		"""获取用户名错误提示"""
		return self._get_error_message(self._locators[ "username_error" ])


	def get_password_error_message (self) -> str:
		"""获取密码错误提示"""
		return self._get_error_message(self._locators[ "password_error" ])


	def _get_error_message (self, locator) -> str:
		"""获取错误提示信息"""
		try:
			error_element = self.driver.find_element(*locator)
			return error_element.text if error_element.is_displayed() else ""
		except:
			return ""